package com.insurance.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.insurance.common.common.ResponseData;
import com.insurance.common.enums.CommonEnum;
import com.insurance.common.utils.JwtOperatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * token过滤器
 *
 * @author Style
 * @version 1.0
 * @date 2020/12/14
 **/
@Slf4j
public class TokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        log.info("【拦截器执行...】");
        PrintWriter out = null;
        try {
            //获取token
            String token = httpServletRequest.getHeader("Authorization");
            if(StringUtils.isBlank(token) || JwtOperatorUtil.isTokenExpired(token)){
                ResponseData errorResponseData = ResponseData.error(CommonEnum.TOKEN_ERROR);
                httpServletResponse.setContentType("application/json;charset=utf-8");
                out = httpServletResponse.getWriter();
                out.write(new ObjectMapper().writeValueAsString(errorResponseData));
                return;
            }else{
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResponseData errorResponseData = ResponseData.error(CommonEnum.TOKEN_ERROR);
            httpServletResponse.setContentType("application/json;charset=utf-8");
            out = httpServletResponse.getWriter();
            out.write(new ObjectMapper().writeValueAsString(errorResponseData));
            return;
        } finally {
            if(out != null){
                log.info("【清空out】");
                out.flush();
                out.close();
            }
        }
    }
}
